import { defineStore } from 'pinia'
import { ref, computed } from 'vue'

// 区域选择器数据接口
interface AreaPickerData {
  label: string
  value: string
  children?: AreaPickerData[]
}

// 接口返回的区域数据接口
interface ApiAreaData {
  id: string
  label: string
  todayCount: number
  lastWeekCount: number
  lastMonthCount: number
  totalCount: number
  children?: ApiAreaData[]
}

export const useAreaPickerStore = defineStore('areaPicker', () => {
  // 区域选择器数据状态
  const areaPickerData = ref<AreaPickerData[]>([])
  const areaPickerDataLoaded = ref(false)
  const areaPickerDataLoading = ref(false)

  // 从本地存储初始化区域选择器数据
  const initAreaPickerData = () => {
    try {
      const stored = uni.getStorageSync('areaPickerData')
      if (stored) {
        areaPickerData.value = stored
        areaPickerDataLoaded.value = true
        console.log('从本地存储加载区域选择器数据成功')
        return true
      }
    } catch (error) {
      console.warn('读取区域选择器数据本地存储失败:', error)
    }
    return false
  }

  // 数据转换函数：将接口数据转换为选择器使用的格式，并添加"全部"选项
  const transformApiDataForPicker = (apiData: ApiAreaData[]): AreaPickerData[] => {
    return apiData.map(item => {
      const processedArea: AreaPickerData = {
        label: item.label,
        value: item.id
      }
      
      // 如果有子区域，递归处理并添加"全部"选项
      if (item.children && item.children.length > 0) {
        const processedChildren = transformApiDataForPicker(item.children)
        processedArea.children = [
          {
            label: '全部',
            value: 'all'
          },
          ...processedChildren
        ]
      }
      
      return processedArea
    })
  }

  // 设置区域选择器数据
  const setAreaPickerData = (data: AreaPickerData[]) => {
    areaPickerData.value = data
    areaPickerDataLoaded.value = true
    
    // 保存到本地存储
    try {
      uni.setStorageSync('areaPickerData', data)
      console.log('区域选择器数据已保存到本地存储')
    } catch (error) {
      console.warn('保存区域选择器数据到本地存储失败:', error)
    }
  }

  // 处理接口数据并转换为选择器格式
  const processApiDataForPicker = (apiData: ApiAreaData[]) => {
    const processedData = transformApiDataForPicker(apiData)
    setAreaPickerData(processedData)
    return processedData
  }

  // 获取区域选择器数据
  const getAreaPickerData = () => {
    return areaPickerData.value
  }

  // 检查数据是否已加载
  const isDataLoaded = () => {
    return areaPickerDataLoaded.value
  }

  // 清除数据
  const clearAreaPickerData = () => {
    areaPickerData.value = []
    areaPickerDataLoaded.value = false
    try {
      uni.removeStorageSync('areaPickerData')
      console.log('区域选择器数据已从本地存储清除')
    } catch (error) {
      console.warn('清除区域选择器数据本地存储失败:', error)
    }
  }

  // 计算属性：区域选择器数据是否可用
  const isAreaPickerDataAvailable = computed(() => {
    return areaPickerDataLoaded.value && areaPickerData.value.length > 0
  })

  // 初始化时尝试从本地存储加载
  initAreaPickerData()

  return {
    // 状态
    areaPickerData,
    areaPickerDataLoaded,
    areaPickerDataLoading,
    isAreaPickerDataAvailable,
    
    // 方法
    setAreaPickerData,
    processApiDataForPicker,
    getAreaPickerData,
    isDataLoaded,
    clearAreaPickerData
  }
})
